package com.vb.webpress.data;

import java.sql.*;

import com.mysql.jdbc.Driver;
import com.vb.webpress.data.Constants.NewsColum;

public class DbManager {
	
	public static Connection getConnection()throws SQLException{
		return getConnection(Constants.DATABASE_NAME, Constants.DATABASE_ACCOUNT, Constants.DATABASE_PASSWORD);
	}
	
	public static Connection getConnection(String dbName, String userName
			, String passWord) throws SQLException {
		String url = "jdbc:mysql://localhost:3306/" + dbName
			+ "?useUnicode=true&characterEncoding=utf-8";
		DriverManager.registerDriver(new Driver());
		return DriverManager.getConnection(url, userName, passWord);
	}
	
	public static boolean createTable(String initialStatement){
		Connection conn = null;
		Statement stm = null;
		try {
			conn = getConnection();
			stm = conn.createStatement();
			stm.execute(initialStatement);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(stm != null)
					stm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
	
	public static boolean insertNewsTable(String type_name, String pic_uris
			, String title, String content, String attachement_uris){
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			conn = getConnection();
			pstm = conn.prepareStatement(NewsColum.NEWS_TABLE_INSERT);
			pstm.setString(1, type_name);
			pstm.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
			pstm.setString(3, pic_uris);
			pstm.setString(4, title);
			pstm.setString(5, content);
			pstm.setString(6, attachement_uris);
			pstm.execute();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(pstm != null)
					pstm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
	public static boolean multiInsertForTest(){
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			conn = getConnection();
			pstm = conn.prepareStatement(NewsColum.NEWS_TABLE_INSERT);
			
			for(int i = 0; i<100; i++){
				pstm.setString(1, "TYPE" + i % 5);
				pstm.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
				pstm.setString(3, "PIC_URIS" + i);
				pstm.setString(4, "TITLE" + i);
				pstm.setString(5, "CONTENT" + i);
				pstm.setString(6, "ATTATCHEMENT_URIS" + i);
				pstm.addBatch();
				
			}
			pstm.executeBatch();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(pstm != null)
					pstm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
}
